package org.example.demo1.servlets.functionPage;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.apache.ibatis.session.SqlSession;
import org.example.demo1.DAO.VisitRecordDao;
import org.example.demo1.Entity.User;
import org.example.demo1.Entity.VisitRecord;
import org.example.demo1.utils.MybatisUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/API/VisitRecord")
public class VisitRecordServlet extends HttpServlet {
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置请求和响应的字符编码
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        Map<String, Object> result = new HashMap<>();
        
        // 获取会话中的用户信息
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        
        // 检查用户是否登录
        if (user == null) {
            result.put("code", 401);
            result.put("msg", "用户未登录");
            out.write(new Gson().toJson(result));
            return;
        }
        
        try {
            // 读取请求体中的JSON数据
            StringBuilder jsonBuilder = new StringBuilder();
            BufferedReader reader = req.getReader();
            String line;
            while ((line = reader.readLine()) != null) {
                jsonBuilder.append(line);
            }
            
            // 解析JSON数据
            JsonObject jsonObject = JsonParser.parseString(jsonBuilder.toString()).getAsJsonObject();
            Integer novelId = jsonObject.get("novelId").getAsInt();
            Integer chapterId = jsonObject.get("chapterId").getAsInt();
            
            // 获取数据库连接
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            VisitRecordDao visitRecordDao = sqlSession.getMapper(VisitRecordDao.class);
            
            try {
                // 首先查找用户在该小说的最新访问记录
                VisitRecord latestRecord = visitRecordDao.findLatestVisitRecordByUserAndNovel(
                        (long) user.getUser_id(), novelId);
                
                if (latestRecord != null) {
                    // 检查是否在5分钟内访问过相同章节
                    VisitRecord recentSameChapter = visitRecordDao.findRecentVisitRecord(
                            (long) user.getUser_id(), chapterId, 5);
                    
                    if (recentSameChapter != null) {
                        // 5分钟内访问过相同章节，只更新时间
                        visitRecordDao.updateVisitTime(recentSameChapter.getVisit_id());
                        result.put("code", 200);
                        result.put("msg", "访问记录已更新");
                    } else {
                        // 更新最新记录为当前章节
                        visitRecordDao.updateVisitRecord(latestRecord.getVisit_id(), chapterId);
                        result.put("code", 200);
                        result.put("msg", "阅读进度已更新");
                    }
                } else {
                    // 创建新的访问记录
                    VisitRecord visitRecord = new VisitRecord(
                            (long) user.getUser_id(), novelId, chapterId);
                    
                    int rowsAffected = visitRecordDao.insertOrUpdateVisitRecord(visitRecord);
                    
                    if (rowsAffected > 0) {
                        result.put("code", 200);
                        result.put("msg", "访问记录保存成功");
                        result.put("data", visitRecord);
                    } else {
                        result.put("code", 500);
                        result.put("msg", "保存访问记录失败");
                    }
                }
                
                sqlSession.commit();
                
            } catch (Exception e) {
                sqlSession.rollback();
                result.put("code", 500);
                result.put("msg", "数据库操作失败: " + e.getMessage());
            } finally {
                sqlSession.close();
            }
            
        } catch (Exception e) {
            result.put("code", 400);
            result.put("msg", "请求参数错误: " + e.getMessage());
        }
        
        out.write(new Gson().toJson(result));
    }
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置请求和响应的字符编码
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        Map<String, Object> result = new HashMap<>();
        
        // 获取会话中的用户信息
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        
        // 检查用户是否登录
        if (user == null) {
            result.put("code", 401);
            result.put("msg", "用户未登录");
            out.write(new Gson().toJson(result));
            return;
        }
        
        try {
            // 获取查询参数
            String novelIdStr = req.getParameter("novelId");
            String limitStr = req.getParameter("limit");
            
            Integer novelId = null;
            Integer limit = 20; // 默认限制20条记录
            
            if (novelIdStr != null && !novelIdStr.isEmpty()) {
                novelId = Integer.parseInt(novelIdStr);
            }
            
            if (limitStr != null && !limitStr.isEmpty()) {
                limit = Integer.parseInt(limitStr);
            }
            
            // 获取数据库连接
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            VisitRecordDao visitRecordDao = sqlSession.getMapper(VisitRecordDao.class);
            
            try {
                List<VisitRecord> visitRecords;
                
                if (novelId != null) {
                    // 获取指定小说的访问记录
                    Map<String, Object> params = new HashMap<>();
                    params.put("userId", user.getUser_id());
                    params.put("novelId", novelId);
                    params.put("limit", limit);
                    visitRecords = visitRecordDao.getVisitRecordsByUserAndNovel(params);
                } else {
                    // 获取用户最近的访问记录
                    visitRecords = visitRecordDao.getRecentVisitRecords((long) user.getUser_id(), limit);
                }
                
                result.put("code", 200);
                result.put("msg", "获取访问记录成功");
                result.put("data", visitRecords);
                
            } catch (Exception e) {
                result.put("code", 500);
                result.put("msg", "数据库查询失败: " + e.getMessage());
            } finally {
                sqlSession.close();
            }
            
        } catch (NumberFormatException e) {
            result.put("code", 400);
            result.put("msg", "参数格式错误");
        } catch (Exception e) {
            result.put("code", 500);
            result.put("msg", "服务器内部错误: " + e.getMessage());
        }
        
        out.write(new Gson().toJson(result));
    }
}